package com.jintoufs.web.action.message;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.sys.Message;
import com.jintoufs.domain.user.User;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.message.MessageService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * Created by xufei on 2017/12/29.
 */
@Controller
@Scope("prototype")
@RequestMapping("/message")
public class MessageAction {

    @Resource
    private MessageService messageService;

    /**
     * 信息查询
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() throws IOException {
        return "message/list";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {

        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String, Object>> list = messageService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(Integer id, Model model) {
        Map<String, Object> entity = null;
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Map<String, Object>> list = messageService.findByMessage(params);

            if (list != null && list.size() > 0) {
                entity = list.get(0);
            }
            isEdit = true;
        } else {
            // 新增
        }

        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", entity);
        return "message/input";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @SystemControllerLog(description = "新增信息")
    public void save(Message message, HttpServletResponse response, @CurrentUser User user) throws ParseException {
        String error = null;
        if (message.getTitle() == null && "".equals(message.getTitle())) {
            error = "信息标题不能为空！";
        }
        if (message.getContent() == null && "".equals(message.getContent())) {
            error = "信息内容不能为空！";
        }
        if (ValidUtil.isEmpty(message.getId())) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = format.format(new Date());
            message.setCreateTime(format.parse(time));
            message.setCreateUserId(user.getId());
        }
        Map<String, Object> result = messageService.save(message);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }


    @RequestMapping("edit")
    @SystemControllerLog(description = "修改信息")
    public void edit(Message message, HttpServletResponse response) {
        Map<String, Object> result = messageService.save(message);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }


    @RequestMapping("delete")
    @SystemControllerLog(description = "删除信息")
    public void delete(HttpServletResponse response, String[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (String _id : id) {
                messageService.delete(Integer.valueOf(_id));
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("该酒店还在营业中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看详细信息")
    public String getDetail(Integer id, Model model) {
        Map<String, Object> result = new HashMap<>();
        if (id != null && id != 0) {
            result = messageService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "详细信息");
        return "message/detail";
    }

    @RequestMapping("/queryList")
    @ResponseBody
    public JqgridPage queryList(int page, int rows, String sidx, String sord, String filters, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String, Object>> list = messageService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/site/detail")
    @ResponseBody
    public Map<String, Object> getDetail2(Integer id, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> result = new HashMap<>();
        if (id != null && id != 0) {
            result = messageService.getById(id);
        }
        return result;
    }

    /**
     * 上一条
     */
    @RequestMapping("/site/prevNews")
    @ResponseBody
    public Map<String, Object> prev(Integer id, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> result = new HashMap<>();
        if (id != null && id != 0) {
            result = messageService.prev(id);
        }
        return result;
    }

    /**
     * 下一条
     */
    @RequestMapping("/site/nextNews")
    @ResponseBody
    public Map<String, Object> next(Integer id, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> result = new HashMap<>();
        if (id != null && id != 0) {
            result = messageService.next(id);
        }
        return result;
    }

    /**
     * 上一页
     */
    @RequestMapping("/site/getPage")
    @ResponseBody
    public List<Map<String, Object>> getPage(int page, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        PageHelper.startPage(page, 4);
        QueryFilters filters_ = null;

        filters_ = new QueryFilters();

        filters_.setSidx("createTime");
        filters_.setSord("desc");
        List<Map<String, Object>> list = messageService.getByFilter(filters_);
        return list;
    }

    /**
     * count
     */
    @RequestMapping("/site//count")
    @ResponseBody
    public int count(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        List list = messageService.queryByParams(null);
        return list.size();
    }
}
